#include "FileManager.h"
#include <fstream>
#include <filesystem>
#include<iostream>
#include "Character.h"
#include "Monster.h"

using json = nlohmann::json;
namespace fs = std::filesystem;
void FileManager::createDirectoryIfNotExists(const std::string& path) {
    fs::path dir(path);
    if (!fs::exists(dir)) {
        fs::create_directories(dir);
    }
}

#pragma region"加载库"

std::vector<User> FileManager::loadUsers(const std::string& filename) {

    std::vector<User> users;
    std::ifstream file(filename);
    if (file.is_open()) {
        try {
            json j;
            file >> j;
            for (const auto& u : j) {
                users.push_back({
                    u.value("id", ""),
                    u.value("password", ""),
                    u.value("isAdmin", false)
                    });
            }
        }
        catch (...) {
            std::cerr << "用户数据解析错误\n";
        }
    }
    return users;
}

bool FileManager::loadGameState(
    const std::string& userId,
    Character*& player,
    std::vector<Monster>& monsters,
    int& currentMonsterIndex)
{
    try {
        // 安全处理用户ID
        
        std::string safeUserId = userId;
        std::replace(safeUserId.begin(), safeUserId.end(), '/', '_');
        std::replace(safeUserId.begin(), safeUserId.end(), '\\', '_');

        // 创建目录
        std::string dir = "data/autosave";
        createDirectoryIfNotExists(dir);

        // 构建安全路径
        fs::path filepath = fs::path(dir) / (safeUserId + ".json");

        std::ifstream file(filepath);
        if (!file.is_open()) {
            std::cerr << "无法打开存档文件: " << filepath << std::endl;
            return false;
        }

        try {
            json j;
            file >> j;
            file.close();

            if (player) {
                delete player;
                player = nullptr;
            }
            player = Character::fromJson(j.at("player"));

            currentMonsterIndex = j.at("currentMonsterIndex").get<int>();

            monsters.clear();
            for (const auto& mj : j.at("monsters")) {
                monsters.push_back(Monster::fromJson(mj));
            }

            return true;
        }
        catch (const std::exception& e) {
            std::cerr << "Error loading game state: " << e.what() << std::endl;
            return false;
        }
    }
    catch (const std::exception& e) {
        std::cerr << "Error in loadGameState: " << e.what() << std::endl;
        return false;
    }
}
std::vector<Equipment> FileManager::loadEquipmentLibrary(const std::string& filename) {
    std::vector<Equipment> equipmentList;

    std::ifstream file(filename);
    if (!file.is_open()) {
        // 文件不存在，创建默认库并保存
        equipmentList = {
            Equipment("勇士之剑", "锋利的宝剑", 10, 0, 0),
            Equipment("魔法法杖", "蕴含魔力的法杖", 5, 2, 0),
            Equipment("生命护符", "增加生命值的护符", 0, 3, 30),
            Equipment("暗影斗篷", "刺客的斗篷", 8, 5, 10),
            Equipment("圣光盾牌", "神圣的盾牌", 3, 15, 20,
                     {Skill("圣光守护", "恢复生命", 0, 20, 25)})
        };

        // 保存默认库
        createDirectoryIfNotExists(fs::path(filename).parent_path().string());
        saveEquipmentLibrary(filename, equipmentList);
        return equipmentList;
    }

    try {
        json j;
        file >> j;

        //std::string jsonStr = j.dump();
        //std::string gbkStr = Utf8ToGbk(jsonStr);
        //j = nlohmann::json::parse(gbkStr);  // 显式指定命名空间

        for (const auto& item : j) {
            equipmentList.push_back(Equipment::fromJson(item));
        }
    }
    catch (const std::exception& e) {
        std::cerr << "Error loading equipment library: " << e.what() << std::endl;
    }

    return equipmentList;
}

std::vector<Skill> FileManager::loadSkillLibrary(const std::string& filename) {
    std::vector<Skill> skillList;

    std::ifstream file(filename);
    if (!file.is_open()) {
        // 文件不存在，创建默认库并保存
        skillList = {
            Skill("火球术", "发射一枚火球", 20, 25, 0),
            Skill("治疗术", "恢复生命值", 25, 30, 0),
            Skill("闪电链", "连锁闪电攻击", 30, 35, 0),
            Skill("冰锥术", "发射冰锥", 22, 28, 0),
            Skill("大地震击", "震撼地面的攻击", 28, 30, 0),
            Skill("风之刃", "快速的风刃攻击", 18, 25, 0),
            Skill("神圣之光", "神圣治疗", 35, 0, 40),
            Skill("毒液喷射", "喷射毒液", 26, 30, 0)
        };

        // 保存默认库
        createDirectoryIfNotExists(fs::path(filename).parent_path().string());
        saveSkillLibrary(filename, skillList);
        return skillList;
    }

    try {
        json j;
        file >> j;

        for (const auto& item : j) {
            skillList.push_back(Skill::fromJson(item));
        }
    }
    catch (const std::exception& e) {
        std::cerr << "Error loading skill library: " << e.what() << std::endl;
    }

    return skillList;
}

std::vector<Monster> FileManager::loadMonsterLibrary(const std::string& filename) {
    std::vector<Monster> monsterList;

    std::ifstream file(filename);
    if (!file.is_open()) {
        // 文件不存在，创建默认怪物库并保存
        monsterList = {
            Monster("哥布林", "弱小的绿色生物", 30, 8, 2),
            Monster("史莱姆", "黏糊糊的怪物", 20, 5, 5),
            Monster("骷髅兵", "复活的骸骨", 40, 10, 3),
            Monster("狼人", "变形的野兽", 60, 15, 5),
            Monster("巨魔", "巨大的怪物", 80, 20, 8),
            
        };

        // 保存默认库
        createDirectoryIfNotExists(fs::path(filename).parent_path().string());
        saveMonsterLibrary(filename, monsterList);
        return monsterList;
    }

    try {
        json j;
        file >> j;

        for (const auto& item : j) {
            monsterList.push_back(Monster::fromJson(item));
        }
    }
    catch (const std::exception& e) {
        std::cerr << "Error loading monster library: " << e.what() << std::endl;
    }

    return monsterList;
}
#pragma endregion


#pragma region"存储"
bool FileManager::saveGameState(
    const std::string& userId,
    const Character& player,
    const std::vector<Monster>& monsters,
    int currentMonsterIndex)
{
    try {
        // 安全处理用户ID
        std::string safeUserId = userId;
        std::replace(safeUserId.begin(), safeUserId.end(), '/', '_');
        std::replace(safeUserId.begin(), safeUserId.end(), '\\', '_');

        // 创建目录
        std::string dir = "data/autosave";
        createDirectoryIfNotExists(dir);

        // 构建安全路径
        fs::path filepath = fs::path(dir) / (safeUserId + ".json");

        json j;
        j["player"] = player.toJson();
        j["currentMonsterIndex"] = currentMonsterIndex;

        json monstersJson = json::array();
        for (const auto& monster : monsters) {
            monstersJson.push_back(monster.toJson());
        }
        j["monsters"] = monstersJson;

        // 写入文件
        std::ofstream file(filepath);
        if (!file.is_open()) {
            std::cerr << "无法打开存档文件: " << filepath << std::endl;
            return false;
        }

        file << j.dump(4);
        return true;
    }
    catch (const std::exception& e) {
        std::cerr << "存档错误: " << e.what() << std::endl;
        return false;
    }
}


bool FileManager::saveEquipmentLibrary(const std::string& filename, const std::vector<Equipment>& equipmentList) {
    try {
        json j = json::array();
        for (const auto& equipment : equipmentList) {
            j.push_back(equipment.toJson());
        }

        std::ofstream file(filename);
        file << j.dump(4);
        return true;
    }
    catch (const std::exception& e) {
        std::cerr << "Error saving equipment library: " << e.what() << std::endl;
        return false;
    }
}

bool FileManager::saveSkillLibrary(const std::string& filename, const std::vector<Skill>& skillList) {
    try {
        json j = json::array();
        for (const auto& skill : skillList) {
            j.push_back(skill.toJson());
        }

        std::ofstream file(filename);
        file << j.dump(4);
        return true;
    }
    catch (const std::exception& e) {
        std::cerr << "Error saving skill library: " << e.what() << std::endl;
        return false;
    }
}

bool FileManager::saveMonsterLibrary(const std::string& filename, const std::vector<Monster>& monsterList) {
    try {
        json j = json::array();
        for (const auto& monster : monsterList) {
            j.push_back(monster.toJson());
        }

        std::ofstream file(filename);
        file << j.dump(4);
        return true;
    }
    catch (const std::exception& e) {
        std::cerr << "Error saving monster library: " << e.what() << std::endl;
        return false;
    }
}


#pragma endregion

